// 测试消消乐游戏交换过程中的匹配检测
// 特别测试左边4列的匹配检测问题

const testMatchDetection = {
  // 创建测试网格
  createTestGrid: function() {
    // 创建一个8x8的测试网格，特别在左边4列放置一些匹配
    const grid = [];
    for (let i = 0; i < 8; i++) {
      const row = [];
      for (let j = 0; j < 8; j++) {
        row.push({
          imageIndex: 0, // 默认为0
          imageUrl: '/test/image0.jpg',
          row: i,
          col: j
        });
      }
      grid.push(row);
    }
    
    // 在左边4列创建一些特定的匹配模式用于测试
    
    // 测试1：第0行，列0-3有4个相同的（应该被检测到）
    grid[0][0].imageIndex = 1;
    grid[0][1].imageIndex = 1;
    grid[0][2].imageIndex = 1;
    grid[0][3].imageIndex = 1;
    
    // 测试2：第2行，列0-2有3个相同的（应该被检测到）
    grid[2][0].imageIndex = 2;
    grid[2][1].imageIndex = 2;
    grid[2][2].imageIndex = 2;
    
    // 测试3：列0，行4-6有3个相同的垂直匹配（应该被检测到）
    grid[4][0].imageIndex = 3;
    grid[5][0].imageIndex = 3;
    grid[6][0].imageIndex = 3;
    
    // 测试4：列1，行0-4有5个相同的垂直匹配（应该被检测到）
    grid[0][1].imageIndex = 4; // 注意：这会覆盖之前的设置
    grid[1][1].imageIndex = 4;
    grid[2][1].imageIndex = 4;
    grid[3][1].imageIndex = 4;
    grid[4][1].imageIndex = 4;
    
    // 测试5：右边也放一些匹配作为对照
    grid[0][5].imageIndex = 5;
    grid[0][6].imageIndex = 5;
    grid[0][7].imageIndex = 5;
    
    return grid;
  },

  // 复制修复后的findMatches函数
  findMatches: function(grid) {
    if (!grid || !Array.isArray(grid)) {
      console.error('无效的网格数据');
      return [];
    }
    
    const gridSize = grid.length;
    let matches = [];
    
    // 检查水平匹配
    for (let i = 0; i < gridSize; i++) {
      if (!grid[i] || !Array.isArray(grid[i])) continue;
      
      let j = 0;
      while (j <= gridSize - 3) { // 修复：改为 <= gridSize - 3，确保j+2不会越界
        // 确保所有单元格都有有效的imageIndex
        if (grid[i][j] && grid[i][j+1] && grid[i][j+2] && 
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i][j+1].imageIndex === 'number' && 
            typeof grid[i][j+2].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i][j+1].imageIndex &&
              grid[i][j].imageIndex === grid[i][j+2].imageIndex) {
            
            // 找到水平匹配的三个或更多
            let matchLength = 3;
            while (j + matchLength < gridSize && 
                   grid[i][j + matchLength] && 
                   typeof grid[i][j + matchLength].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i][j+matchLength].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              // 检查是否已经添加过这个方块
              const existingMatch = matches.find(m => m.row === i && m.col === j + k);
              if (!existingMatch) {
                matches.push({ row: i, col: j + k, type: 'horizontal', length: matchLength });
              }
            }
            
            j += matchLength; // 跳过已匹配的方块
          } else {
            j++;
          }
        } else {
          j++;
        }
      }
    }
    
    // 检查垂直匹配
    for (let j = 0; j < gridSize; j++) {
      let i = 0;
      while (i <= gridSize - 3) { // 修复：改为 <= gridSize - 3，确保i+2不会越界
        // 确保所有单元格都有有效的imageIndex
        if (grid[i] && grid[i+1] && grid[i+2] && 
            grid[i][j] && grid[i+1][j] && grid[i+2][j] &&
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i+1][j].imageIndex === 'number' && 
            typeof grid[i+2][j].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i+1][j].imageIndex &&
              grid[i][j].imageIndex === grid[i+2][j].imageIndex) {
            
            // 找到垂直匹配的三个或更多
            let matchLength = 3;
            while (i + matchLength < gridSize && 
                   grid[i + matchLength] && 
                   grid[i + matchLength][j] &&
                   typeof grid[i + matchLength][j].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i+matchLength][j].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              // 检查是否已经添加过这个方块
              const existingMatch = matches.find(m => m.row === i + k && m.col === j);
              if (!existingMatch) {
                matches.push({ row: i + k, col: j, type: 'vertical', length: matchLength });
              }
            }
            
            i += matchLength; // 跳过已匹配的方块
          } else {
            i++;
          }
        } else {
          i++;
        }
      }
    }
    
    return matches;
  },

  // 运行测试
  runTest: function() {
    console.log('=== 匹配检测测试开始 ===');
    
    const grid = this.createTestGrid();
    
    // 打印网格状态
    console.log('测试网格布局:');
    for (let i = 0; i < 8; i++) {
      let row = '';
      for (let j = 0; j < 8; j++) {
        row += grid[i][j].imageIndex + ' ';
      }
      console.log(`行${i}: ${row}`);
    }
    
    // 运行匹配检测
    const matches = this.findMatches(grid);
    
    console.log(`\n检测到的匹配数量: ${matches.length}`);
    
    // 分析匹配结果
    const expectedMatches = [
      { description: '第0行，列0-3的4个水平匹配', type: 'horizontal', count: 4 },
      { description: '第2行，列0-2的3个水平匹配', type: 'horizontal', count: 3 },
      { description: '列0，行4-6的3个垂直匹配', type: 'vertical', count: 3 },
      { description: '列1，行0-4的5个垂直匹配', type: 'vertical', count: 5 },
      { description: '第0行，列5-7的3个水平匹配', type: 'horizontal', count: 3 }
    ];
    
    if (matches.length > 0) {
      console.log('\n详细匹配信息:');
      matches.forEach((match, index) => {
        console.log(`匹配 ${index+1}: 位置(${match.row},${match.col}), 类型: ${match.type}, 长度: ${match.length || '未知'}`);
      });
      
      // 按类型分组统计
      const horizontalMatches = matches.filter(m => m.type === 'horizontal');
      const verticalMatches = matches.filter(m => m.type === 'vertical');
      
      console.log(`\n统计结果:`);
      console.log(`水平匹配: ${horizontalMatches.length} 个`);
      console.log(`垂直匹配: ${verticalMatches.length} 个`);
      
      // 检查左边4列的匹配
      const leftColumnMatches = matches.filter(m => m.col <= 3);
      console.log(`左边4列匹配: ${leftColumnMatches.length} 个`);
      
      if (leftColumnMatches.length > 0) {
        console.log('✅ 左边4列的匹配被正确检测到');
      } else {
        console.log('❌ 左边4列的匹配未被检测到');
      }
      
    } else {
      console.log('❌ 没有检测到任何匹配，这是不正确的');
    }
    
    // 验证预期匹配
    console.log('\n=== 预期匹配验证 ===');
    let allExpectedFound = true;
    
    // 这里简化验证，实际应该检查具体的匹配组合
    if (matches.length >= 15) { // 预期总共应该有15+个匹配的方块
      console.log('✅ 匹配数量符合预期');
    } else {
      console.log('❌ 匹配数量不符合预期');
      allExpectedFound = false;
    }
    
    return {
      success: allExpectedFound && leftColumnMatches.length > 0,
      totalMatches: matches.length,
      leftColumnMatches: leftColumnMatches.length,
      matches: matches
    };
  }
};

// 运行测试
console.log('开始测试匹配检测逻辑...');
testMatchDetection.runTest();